const base64Pad = '=';
const toBase64Table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

export default (data: string) => {

    let result = '';

    let length = data.length;

    let i;

    for (i = 0; i < (length - 2); i += 3) {

        result += toBase64Table[data.charCodeAt(i) >> 2];

        result += toBase64Table[((data.charCodeAt(i) & 0x03) << 4) + (data.charCodeAt(i + 1) >> 4)];

        result += toBase64Table[((data.charCodeAt(i + 1) & 0x0f) << 2) + (data.charCodeAt(i + 2) >> 6)];

        result += toBase64Table[data.charCodeAt(i + 2) & 0x3f];

    }

    if (length % 3) {

        i = length - (length % 3);

        result += toBase64Table[data.charCodeAt(i) >> 2];

        if ((length % 3) === 2) {

            result += toBase64Table[((data.charCodeAt(i) & 0x03) << 4) + (data.charCodeAt(i + 1) >> 4)];

            result += toBase64Table[(data.charCodeAt(i + 1) & 0x0f) << 2];

            result += base64Pad;

        } else {

            result += toBase64Table[(data.charCodeAt(i) & 0x03) << 4];

            result += base64Pad + base64Pad;

        }

    }
    return result;
}
